# utils.py - 工具模块
import logging
import base64
import os
import ssl
from io import BytesIO
import matplotlib.pyplot as plt
import pandas as pd
import pdfkit
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import smtplib

from config import CONFIG
from utils.logger_util import logger

COMMASPACE = ', '
def setup_logger():
    """配置日志系统"""
    logging.basicConfig(
        filename=CONFIG['logging']['log_file'],
        level=getattr(logging, CONFIG['logging']['level']),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    return logging.getLogger(__name__)


def generate_chart(data:pd.DataFrame,x_label="类别",y_label="数值",title="示例图表"):
    """生成示例图表"""
    try:
        plt.figure(figsize=(14, 10))
        plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei']  # 设置中文支持
        plt.rcParams['axes.unicode_minus'] = False
        plt.bar(data[x_label], data[y_label])
        plt.title(title)
        plt.xlabel(x_label)
        plt.ylabel(y_label)

        # 保存到内存
        img_data = BytesIO()
        plt.savefig(img_data, format='png')
        plt.close()
        return base64.b64encode(img_data.getvalue()).decode('utf-8')
    except Exception as e:
        logger.error(f"生成图表失败: {str(e)}")
        return None


def generate_pdf(html_content, output_path):
    """生成PDF文件"""
    try:
        config = pdfkit.configuration(wkhtmltopdf=CONFIG['pdf']['wkhtmltopdf_path'])
        options = {
            'encoding': "UTF-8",
            'enable-local-file-access': None,
            'margin-top': '0.75in',
            'margin-right': '0.75in',
            'margin-bottom': '0.75in',
            'margin-left': '0.75in'
        }
        pdfkit.from_string(html_content, output_path, configuration=config, options=options)
        return output_path
    except Exception as e:
        logger.error(f"生成PDF失败: {str(e)}")
        return None


def send_email(subject, recipients, html_content, attachments=None):
    """发送邮件"""
    try:
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = CONFIG['email']['sender_email']
        msg['To'] = COMMASPACE.join(recipients)

        # 添加HTML正文
        msg.attach(MIMEText(html_content, 'html'))

        # 添加附件
        for file in (attachments or []):
            part = MIMEBase('application', "octet-stream")
            with open(file, "rb") as f:
                part.set_payload(f.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            f'attachment; filename="{os.path.basename(file)}"')
            msg.attach(part)

        # 发送邮件
        context = ssl.create_default_context()
        context.minimum_version = ssl.TLSVersion.TLSv1_2  # Python 3.7+
        smtp_params = {
            'host': CONFIG['email']['smtp_server'],
            'port': CONFIG['email']['smtp_port'],
            'context':context,  # 关键修复
            'timeout' : 100
        }

        if CONFIG['email']['use_ssl']:
            with smtplib.SMTP_SSL(**smtp_params) as server:
                server.login(CONFIG['email']['sender_email'], CONFIG['email']['sender_password'])
                server.sendmail(CONFIG['email']['sender_email'], recipients,msg.as_string())
        else:
            with smtplib.SMTP(**smtp_params) as server:
                server.starttls()
                server.login(CONFIG['email']['sender_email'], CONFIG['email']['sender_password'])
                server.sendmail(CONFIG['email']['sender_email'], recipients, msg.as_string())

        return True
    except Exception as e:
        logger.error(f"发送邮件失败: {str(e)}")
        return False